#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/3/28 20:50
# @Author  : LiMC
# @File    : books.py
# @Software: PyCharm
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/ceshi1?charset=utf8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True


db = SQLAlchemy(app)

class Author(db.Model):

    __tablename__ = 'authors'

    id = db.Column(db.Integer, primary_key=True, )
    name = db.Column(db.String(16), unique=True)
    # 关系引用
    book = db.relationship('Book', backref="authors")

    def __repr__(self):
        return "Author:{}".format(self.name)


class Book(db.Model):

    __tablename__ = 'books'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30), unique=True)
    author_id = db.Column(db.Integer, db.ForeignKey('authors.id'))

    def __repr__(self):
        return "Book:{},{}".format(self.name, self.author_id)


# @app.route('/')
# def index():
#     authors = Author.query.all()
#     books = Book.query.all()
#
#     return render_template('index.html', authors=authors, books=books)


if __name__ == '__main__':
    db.drop_all()
    db.create_all()

    au1 = Author(name='lmc')
    au2 = Author(name='Nini')

    db.session.add_all([au1, au2])
    #
    bk1 = Book(name="lmc", author_id=au1.id)
    bk2 = Book(name="lmc1", author_id=au1.id)
    bk3 = Book(name="NINI1", author_id=au2.id)
    bk4 = Book(name="nini2", author_id=au2.id)
    bk5 = Book(name="nini3", author_id=au2.id)

    db.session.add_all([bk2, bk2, bk3, bk4, bk5])
    # #
    # # bk = Book(name='李明昌', author_id=au1.id)

    db.session.commit()

    app.run()